using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using LibVLCSharp.Shared;
using LibVLCSharp.WinForms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;

namespace xianshi2
{
    public partial class MainForm : Form
    {
        private LibVLC _libVLC;
        private Panel panelView;
        private Panel controlPanel;
        private Button btnMES;
        private Button btnMonitor;
        private const int Rows = 2;
        private const int Columns = 3;
        private VideoView[] _videoViews = new VideoView[Rows * Columns];
        private MediaPlayer[] _mediaPlayers = new MediaPlayer[Rows * Columns];
        private WebView2 webView;
        private bool isMESMode = false;
        private bool webViewInitialized = false;

        // 摄像头URL
        private readonly string[] _cameraUrls = {
            "rtsp://admin:cjjg1234@172.24.114.132:554/h264/ch1/main/av_stream",
            "rtsp://admin:cjjg1234@172.24.114.168:554/h264/ch2/main/av_stream",
            "rtsp://admin:cjjg1234@172.24.114.170:554/h264/ch3/main/av_stream",
            "rtsp://admin:cjjg1234@172.24.114.130:554/h264/ch4/main/av_stream",
            "rtsp://admin:cjjg1234@172.24.114.162:554/h264/ch5/main/av_stream",
            "rtsp://admin:cjjg1234@172.24.114.159:554/h264/ch6/main/av_stream"
        };

        // MES系统URL
        private const string MES_URL = "https://ah-mes.jgsteel.cn/test/jgjjsc";

        public MainForm()
        {
            // 初始化VLC库
            Core.Initialize();

            // 创建主Panel
            panelView = new Panel
            {
                Dock = DockStyle.Fill
            };

            // 创建控制按钮面板
            controlPanel = new Panel
            {
                Dock = DockStyle.Bottom,
                Height = 60,
                BackColor = Color.FromArgb(30, 30, 30)
            };

            // 创建MES系统按钮
            btnMES = new Button
            {
                Text = "MES系统",
                Font = new Font("微软雅黑", 12F, FontStyle.Bold),
                ForeColor = Color.White,
                BackColor = Color.FromArgb(40, 96, 144),
                FlatStyle = FlatStyle.Flat,
                Size = new Size(150, 40),
                Location = new Point((panelView.Width - 320) / 2, 10)
            };
            btnMES.FlatAppearance.BorderSize = 0;
            btnMES.MouseEnter += (sender, e) => { btnMES.BackColor = Color.FromArgb(50, 116, 174); };
            btnMES.MouseLeave += (sender, e) => { btnMES.BackColor = Color.FromArgb(40, 96, 144); };
            btnMES.Click += BtnMES_Click;

            // 创建实时监控按钮
            btnMonitor = new Button
            {
                Text = "实时监控",
                Font = new Font("微软雅黑", 12F, FontStyle.Bold),
                ForeColor = Color.White,
                BackColor = Color.FromArgb(40, 96, 144),
                FlatStyle = FlatStyle.Flat,
                Size = new Size(150, 40),
                Location = new Point((panelView.Width + 20) / 2, 10)
            };
            btnMonitor.FlatAppearance.BorderSize = 0;
            btnMonitor.MouseEnter += (sender, e) => { btnMonitor.BackColor = Color.FromArgb(50, 116, 174); };
            btnMonitor.MouseLeave += (sender, e) => { btnMonitor.BackColor = Color.FromArgb(40, 96, 144); };
            btnMonitor.Click += BtnMonitor_Click;

            controlPanel.Controls.Add(btnMES);
            controlPanel.Controls.Add(btnMonitor);

            // 添加控件到窗体
            Controls.Add(panelView);
            Controls.Add(controlPanel);

            // 创建LibVLC实例
            _libVLC = new LibVLC("--network-caching=1000", "--live-caching=300");

            // 设置窗体属性
            Text = "多摄像头监控";
            StartPosition = FormStartPosition.CenterScreen;
            WindowState = FormWindowState.Maximized;

            // 添加窗体大小改变事件
            Resize += MainForm_Resize;

            // 初始化摄像头网格
            InitializeCameraGrid();

            // 初始化WebView2
            InitializeWebView();

            // 启动即全屏
            ToggleFullScreen();
        }

        private async void InitializeWebView()
        {
            try
            {
                // 初始化WebView2环境
                await EnsureWebView2Async();

                // 创建WebView2控件
                webView = new WebView2
                {
                    Dock = DockStyle.Fill,
                    Visible = false
                };

                panelView.Controls.Add(webView);

                // 确保WebView2完全初始化
                await webView.EnsureCoreWebView2Async(null);
                webViewInitialized = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化WebView2失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task EnsureWebView2Async()
        {
            // 检查并确保WebView2运行时已安装
            var env = await CoreWebView2Environment.CreateAsync(null, null);
        }

        private void BtnMES_Click(object sender, EventArgs e)
        {
            if (!isMESMode)
            {
                // 切换到MES系统模式
                HideCameraViews();

                if (webView != null && webViewInitialized)
                {
                    webView.Visible = true;
                    webView.BringToFront();

                    if (webView.CoreWebView2 != null)
                    {
                        webView.CoreWebView2.Navigate(MES_URL);
                    }
                }

                isMESMode = true;
                UpdateButtonStyles();
            }
        }

        private void BtnMonitor_Click(object sender, EventArgs e)
        {
            if (isMESMode)
            {
                // 切换到监控模式
                if (webView != null)
                {
                    webView.Visible = false;
                }

                ShowCameraViews();
                isMESMode = false;
                UpdateButtonStyles();
            }
        }

        private void UpdateButtonStyles()
        {
            if (isMESMode)
            {
                btnMES.BackColor = Color.FromArgb(25, 135, 84); // 绿色表示激活
                btnMonitor.BackColor = Color.FromArgb(40, 96, 144);
            }
            else
            {
                btnMES.BackColor = Color.FromArgb(40, 96, 144);
                btnMonitor.BackColor = Color.FromArgb(25, 135, 84); // 绿色表示激活
            }
        }

        private void HideCameraViews()
        {
            for (int i = 0; i < Rows * Columns; i++)
            {
                _videoViews[i].Visible = false;
            }
        }

        private void ShowCameraViews()
        {
            for (int i = 0; i < Rows * Columns; i++)
            {
                _videoViews[i].Visible = true;
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            // 更新按钮位置
            btnMES.Location = new Point((panelView.Width - 320) / 2, 10);
            btnMonitor.Location = new Point((panelView.Width + 20) / 2, 10);

            UpdateCameraLayout();
        }

        private void ToggleFullScreen()
        {
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;
            Bounds = Screen.PrimaryScreen.Bounds;

            UpdateCameraLayout();
        }

        private void InitializeCameraGrid()
        {
            // 预创建所有视频视图
            for (int i = 0; i < Rows * Columns; i++)
            {
                _mediaPlayers[i] = new MediaPlayer(_libVLC);

                _videoViews[i] = new VideoView
                {
                    MediaPlayer = _mediaPlayers[i],
                    Dock = DockStyle.Fill
                };

                // 创建容器Panel
                Panel container = new Panel
                {
                    Dock = DockStyle.Fill,
                    Padding = new Padding(1) // 最小化间距
                };

                container.Controls.Add(_videoViews[i]);
                panelView.Controls.Add(container);
            }

            // 初始布局
            UpdateCameraLayout();

            // 使用任务并行库同时加载所有摄像头
            Task.WhenAll(LoadAllCameras());
        }

        private void UpdateCameraLayout()
        {
            // 计算每个摄像头面板的行列数
            for (int i = 0; i < Rows * Columns; i++)
            {
                int row = i / Columns;
                int col = i % Columns;

                // 获取容器Panel
                Panel container = (Panel)panelView.Controls[i];

                // 设置停靠方式以实现自适应布局
                container.Dock = DockStyle.None;
                container.Location = new Point(col * (panelView.Width / Columns),
                                              row * (panelView.Height / Rows));
                container.Size = new Size(panelView.Width / Columns,
                                         panelView.Height / Rows);
            }
        }

        private Task[] LoadAllCameras()
        {
            var tasks = new Task[Rows * Columns];

            for (int i = 0; i < Rows * Columns; i++)
            {
                int index = i; // 捕获循环变量
                tasks[i] = Task.Run(() => LoadCameraStream(index));
            }

            return tasks;
        }

        private async Task LoadCameraStream(int index)
        {
            try
            {
                using var media = new Media(_libVLC, new Uri(_cameraUrls[index]));

                // 添加网络优化选项
                media.AddOption(":network-caching=800"); // 降低缓存减少延迟
                media.AddOption(":rtsp-tcp"); // 使用TCP提高可靠性
                media.AddOption(":clock-jitter=0");
                media.AddOption(":clock-synchro=0");

                // 播放视频
                await Task.Run(() => _mediaPlayers[index].Play(media));
            }
            catch (Exception ex)
            {
                // 在UI线程上显示错误
                Invoke(new Action(() =>
                {
                    MessageBox.Show($"加载摄像头 {index + 1} 失败: {ex.Message}", "错误");
                }));
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 释放所有资源
            for (int i = 0; i < Rows * Columns; i++)
            {
                _mediaPlayers[i]?.Stop();
                _mediaPlayers[i]?.Dispose();
            }

            _libVLC.Dispose();

            base.OnFormClosing(e);
        }
    }
}